package activities;

/*
 * Detects Biceps Curls
 */

import helper.Exercise;
import helper.ExercisesEnum;
import helper.Settings;
import helper.SharedPreferencesHelper;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.example.intellifit.R;

public class RepetitionsActivityCurls extends RepetitionsActivity implements
		OnClickListener, SensorEventListener {

	static final float lowerBound = 20;
	static final float upperBound = -20;
	static final float zero = 0;
	static boolean firstTime = true;

	public enum orientationStateEnum {
		AT_TOP, NOWHERELAND_COMING_FROM_TOP, NOWHERELAND_COMING_FROM_BOTTOM, AT_BOTTOM
	}

	static orientationStateEnum orientation, orientation_last;

	/* --END SENSORS */

	private Spinner spinner;
	private String[] viewSelection;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.view_repetions_include);
		vf = (ViewFlipper) findViewById(R.id.vf);
		thislistener = this;

		RelativeLayout rl = (RelativeLayout) findViewById(R.id.overlay);
		rl.setBackgroundResource(R.drawable.bg_curl_tap_to);
		
		this.currentExercise = new Exercise(11, "Biceps Curls");
		this.exerciseType = ExercisesEnum.BICEP_CURLS;

		sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		super.initLayoutComponents();
		registerListeners();
		gDetector = new GestureDetector(this, this);

		// initialize sharedPreferences before overlays are shown
		spHelper = new SharedPreferencesHelper(this);

		if (spHelper.mustShowExerciseInformation(this.exerciseType)) {
			showExerciseInfo();
		}
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		registerListeners();
	}

	// use deprecated for backward compatibility
	@SuppressWarnings("deprecation")
	@Override
	public void reInit() {
		super.reInit();
		sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		sManager.registerListener(this,
				sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);
	}

	@SuppressWarnings("deprecation")
	public void registerListeners() {

		sManager.registerListener(this,
				sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);
		Log.i("MALA", "--- registering type_orientation listener");
		findViewById(R.id.overlay).setOnClickListener(this);
		findViewById(R.id.overlayStopExercise).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (started) {
							sManager.unregisterListener(thislistener);
							Settings.getInstance().lastExerciseDone = currentExercise;
							endTimeNS = System.nanoTime();
							updateDB();
							if (repetitions > 0) {
								Toast.makeText(
										getBaseContext(),
										"Congratulations! You've just completed "
												+ repetitions + " repetitions.",
										Toast.LENGTH_LONG).show();
							}
							
							repetitions = 0;
							executionAccuracy = 0;

							createStatisticOverlay(false);

						}
					}
				});
	}

	@Override
	protected void onPause() {
		super.onPause();
		started = false;
		this.sManager.unregisterListener(this);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		if (!db_uptoDate)
			updateDB();
	}

	@Override
	public void onClick(View v) {
		overlay.setVisibility(View.INVISIBLE);
		overlayCountdown.setBackgroundResource(R.drawable.bg_curl);
		overlayStopExercise.setBackgroundResource(R.drawable.bg_curl);
		startCountDown();
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		Log.i("MALA", "---> vor started <---");
		if (started) {
			Log.i("MALA", " ----------- started ------------");
			switch (event.sensor.getType()) {
			case Sensor.TYPE_ORIENTATION:
				float axe = event.values[1];
				long currTime = System.currentTimeMillis();

				// initial position
				if (firstTime) {
					if (axe < upperBound) {
						orientation = orientationStateEnum.AT_TOP;
					} else if (axe > lowerBound) {
						orientation = orientationStateEnum.AT_BOTTOM;
					} else {
						orientation = orientationStateEnum.NOWHERELAND_COMING_FROM_BOTTOM;
					}
					firstTime = false;
				}

				if (axe < lowerBound && axe > upperBound) {
					if (orientation == orientationStateEnum.AT_BOTTOM) {
						orientation = orientationStateEnum.NOWHERELAND_COMING_FROM_BOTTOM;
					}
					if (orientation == orientationStateEnum.AT_TOP) {
						orientation = orientationStateEnum.NOWHERELAND_COMING_FROM_TOP;
					}
				}

				Log.i("MALA", orientation.toString());

				if (axe > lowerBound
						&& orientation == orientationStateEnum.NOWHERELAND_COMING_FROM_TOP) {

					long dif = currTime - lastRepetitionTime;
					if (repetitions > 0) {
						Log.d("REP", "Time between: " + dif);
						if (dif > this.repetition_duratation + 1300) { // 3800
							Log.d("REP", "FASTER");
							try {
								mPlayer = MediaPlayer
										.create(this, R.raw.faster);
								mPlayer.setLooping(false);
								mPlayer.start();
								mPlayer.setOnCompletionListener(new OnCompletionListener() {
									public void onCompletion(MediaPlayer mp) {
										mPlayer.release();
									};
								});
							} catch (Exception e) {
								e.printStackTrace();
							}

						} else if (dif < this.repetition_duratation - 800) { // 1700
							Log.d("REP", "SLOWER");
							try {
								mPlayer = MediaPlayer
										.create(this, R.raw.slower);
								mPlayer.setLooping(false);
								mPlayer.start();
								mPlayer.setOnCompletionListener(new OnCompletionListener() {
									public void onCompletion(MediaPlayer mp) {
										mPlayer.release();
									};
								});
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							executionAccuracy++;
						}
					}
					lastRepetitionTime = currTime;
					repetitions++;
					reps++;
					updateCurrRepsView(reps);
				}

				if (axe < upperBound) {
					orientation = orientationStateEnum.AT_TOP;
				}

				if (axe > lowerBound) {
					orientation = orientationStateEnum.AT_BOTTOM;
				}

				break;

			}
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

}
